import 'dart:async';
import 'dart:convert';

import 'package:ble_demo/ble/ble_action_type.dart';
import 'package:ble_demo/ble/ble_device.dart';
import 'package:ble_demo/ble/ble_plugin.dart';
import 'package:ble_demo/entity/smart_device.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ble_demo/http/index.dart';

/**
 * 设备列表
 */
class DeviceDisplayData extends StatefulWidget {
  //智能设备
  SmartDevice smartDevice;

  DeviceDisplayData(this.smartDevice);

  @override
  State<StatefulWidget> createState() => DeviceDisplayDataState();
}

class DeviceDisplayDataState extends State<DeviceDisplayData>  with WidgetsBindingObserver{
//显示结果
  String data = "0.0";
  DateTime _dateTime = DateTime.now();
  Timer _timer;
  var dataFormat = DateFormat("yyyy-MM-dd HH:mm:ss");
  String showTime = "";
  //设备是否可用
  bool isEnable = false;
  //设备本地存储器
  Future<SharedPreferences> _device_prefs = SharedPreferences.getInstance();
  String uuid_service;
  String uuid_characteristic_notify;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    //未绑定直接显示数据
    setState(() {
      isEnable = !widget.smartDevice.isStoreLocal;
    });
    //计时器
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _dateTime = DateTime.now();
        showTime = dataFormat.format(_dateTime);
      });
    });

    /// ble监听初始化
    BlePlugin.addListener(onBleListener);

    switch (widget.smartDevice.deviceType) {
      case SmartDeviceType.BODY_GUN:
        _connectByMac();
        break;
      case SmartDeviceType.BODY_FAT:
        _scanFatDevice();
        break;
    }
  }

  /**
   *绑定用户
   */
  _bindDeviceByUserId(String mac) async {
    final SharedPreferences prefs = await _device_prefs;
    String userId = "123456";
    //todo
    //发送请求然后绑定到服务器
    int deviceType = 1;
    switch (widget.smartDevice.deviceType) {
      case SmartDeviceType.BODY_GUN:
        deviceType = 2;
        break;
      case SmartDeviceType.BODY_FAT:
        deviceType = 3;
        break;
    }
    DeviceHttp.checkBind({"sn": mac, "device_type": deviceType}).then((result) {

     if(result!=null){
       int resultCode = jsonDecode(result)["data"]["res"];
       if(resultCode == 0){//设备未绑定
         DeviceHttp.bind({"sn": mac, "device_type": deviceType}).then((value) {
           if(value == 200 ){
             prefs.setString(mac, userId);
           }else{
             EasyLoading.showError("设备绑定失败!");
           }
         });
       }else if(resultCode == 1){//被自己绑定
         print("===设备被自己绑定===");
       }else if(resultCode == 2){
         EasyLoading.showError("设备已经被别人绑定，请先解绑!");
       }
     }
    });
  }
  // 接受体脂秤
  _scanFatDevice() {
    BlePlugin.scan();
  }
  _cancelScan(){
    BlePlugin.cancelScan();
  }

  //根据mac地址连接设备
  _connectByMac() {
    BlePlugin.connectByMac(bleDevice: BleDevice(mac: widget.smartDevice.mac));
  }
  _stopNotify(){
    BlePlugin.stopNotify(
        bleDevice: BleDevice(mac: widget.smartDevice.mac),
        uuid_service: uuid_service,
        uuid_characteristic_notify: uuid_characteristic_notify);
  }

  //连接成功后读取数据
  _notify() {
    BlePlugin.notify(
        bleDevice: BleDevice(mac: widget.smartDevice.mac),
        uuid_service: uuid_service,
        uuid_characteristic_notify: uuid_characteristic_notify);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      ///开始连接
      switch (widget.smartDevice.deviceType) {
        case SmartDeviceType.BODY_GUN:
          _connectByMac();
          break;
        case SmartDeviceType.BODY_FAT:
          _scanFatDevice();
          break;
      }
    } else if (state == AppLifecycleState.paused) {
      //取消通知
      switch (widget.smartDevice.deviceType) {
        case SmartDeviceType.BODY_GUN:
          _stopNotify();
          break;
        case SmartDeviceType.BODY_FAT:
          _cancelScan();
          break;
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color(0xffeeeeee),
        appBar: AppBar(
            centerTitle: true,
            actions: [
              FlatButton(
                  onPressed: () {},
                  child: Text(
                    "设备详情",
                    style: TextStyle(color: Colors.orangeAccent, fontSize: 18),
                  ))
            ],
            title: Text(
              widget.smartDevice.deviceType == SmartDeviceType.BODY_FAT
                  ? "测量体重"
                  : "测量体温",
              style: TextStyle(color: Colors.black),
            )),
        body: _buildDisplayDataWidget(context, widget.smartDevice.deviceType));
  }

  /// 销毁
  @override
  dispose() {
    WidgetsBinding.instance.removeObserver(this);
    BlePlugin.removeListener(onBleListener);
    if (_timer != null) {
      _timer.cancel();
    }
    super.dispose();
  }

  onBleListener(type, params) {
    print("type=$type========params=$params");

    //读取成功
    if (type == BleActionType.READ_SUCCESS) {
      String result = params["data"];
      setState(() {
        isEnable = true;
        data = result;
      });
    } else if (type == BleActionType.FAIL) {
      EasyLoading.showError("读取失败，请重试!");
    } //体脂秤回调
    else if (type == BleActionType.ONLESCAN) {
      print("体脂秤回调===========params=$params");
      //显示结果
      String weight = jsonDecode(params)["weight"]; //体重
      String impedance = jsonDecode(params)["impedance"]; //阻抗
      String isLock = jsonDecode(params)["isLock"]; //是否最终值 AA或者AB即是，需要上传数据
      String mac = jsonDecode(params)["mac"]; //设备mac地址
      setState(() {
        isEnable = true;
        data = weight;
      });
      //绑定用户
      _bindDeviceByUserId(mac);
    } else if (type == BleActionType.CONNECT_SUCCESS) {
      String mac = jsonDecode(params)["bleDevice"]["mac"];
      setState(() {
        widget.smartDevice =
            SmartDevice(deviceType: SmartDeviceType.BODY_GUN, mac: mac);
        uuid_service = jsonDecode(params)["uuid_service"];
        uuid_characteristic_notify =
            jsonDecode(params)["uuid_characteristic_notify"];
      });
      //绑定用户
      _bindDeviceByUserId(mac);
       Future.delayed(Duration(seconds: 2),(){
         //读取数据
         _notify();
       });
    } else if (type == BleActionType.CONNECT_FAIL) {
      EasyLoading.showSuccess('连接失败!');
    }
  }

  //测量显示数据widget
  _buildDisplayDataWidget(
      BuildContext context, SmartDeviceType smartDeviceType) {
    return Padding(
        padding: const EdgeInsets.all(10),
        child: Center(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
              isEnable
                  ? _buildShowData(context, smartDeviceType)
                  : _buildDefaultState(context, smartDeviceType),
              Text(
                smartDeviceType == SmartDeviceType.BODY_FAT ? "双脚上秤" : "对准眉心",
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              ),
              Padding(
                  padding: const EdgeInsets.all(10),
                  child: Text(smartDeviceType == SmartDeviceType.BODY_FAT
                      ? "上秤后，秤上会显示体重信息"
                      : "按下测量按键，一键实现体温测量"))
            ])));
  }

  //设备连接之前
  _buildDefaultState(BuildContext context, SmartDeviceType smartDeviceType) {
    return smartDeviceType == SmartDeviceType.BODY_FAT
        ? Image.asset("assets/images/img_weight.png", fit: BoxFit.contain)
        : Image.asset("assets/images/img_temp.png", fit: BoxFit.contain);
  }

  //连接成功显示数据
  _buildShowData(BuildContext context, SmartDeviceType smartDeviceType) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        smartDeviceType == SmartDeviceType.BODY_FAT
            ? Image.asset("assets/images/img_ring_green.png",
                fit: BoxFit.contain)
            : Image.asset("assets/images/img_ring_blue.png",
                fit: BoxFit.contain),
        Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10),
              child: Text("$showTime"),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  "$data",
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 10),
                  child: Text(
                    smartDeviceType == SmartDeviceType.BODY_FAT ? "公斤" : "摄氏度",
                  ),
                )
              ],
            ),
            Padding(
                padding: const EdgeInsets.all(10),
                child: Text(smartDeviceType == SmartDeviceType.BODY_FAT
                    ? "体重(kg)"
                    : "体温(℃)")),
          ],
        )
      ],
    );
  }
}

